//
// Created by antler on 2018/12/20.
//

#include "UIUtils.h"

#include "LuaJavaHelper.h"

static jmethodID methodID_UI_createContext = nullptr;

namespace UIUtils {

    void toast(const std::string &msg, int length) {
        do {
            JNIEnv *env = LuaJavaHelper::getInstance()->getEnv();
            if (!env) {
                break;
            }

            ScopedLocalRef<jstring> jmsg(env, env->NewStringUTF(msg.c_str()));
            if (jmsg) {
                LuaJavaHelper::callStaticVoidMethod(env, CLASS_NAME_UI, METHOD_NAME_UI_TOAST,
                                                    METHOD_SIG_UI_TOAST, (jstring) jmsg, length);
            }
        } while (0);
    }

    jobject createContext(const std::string &layout, const std::string &style) {
        jobject juicontext = nullptr;
        do {
            JNIEnv *env = LuaJavaHelper::getInstance()->getEnv();
            if (!env) {
                break;
            }

            ScopedLocalRef<jclass> localClassUIContext(env, env->FindClass(CLASS_NAME_UICONTEXT));
            if (!localClassUIContext) {
                break;
            }

            if (methodID_UI_createContext == nullptr) {
                methodID_UI_createContext = env->GetStaticMethodID(localClassUIContext,
                                                                   METHOD_NAME_UICONTEXT_CREATECONTEXT,
                                                                   METHOD_SIG_UICONTEXT_CREATECONTEXT);
            }

            if (!methodID_UI_createContext) {
                assert(0);
                break;
            }

            ScopedLocalRef<jstring> jlayout(env, env->NewStringUTF(layout.c_str()));
            ScopedLocalRef<jstring> jstyle(env, env->NewStringUTF(style.c_str()));
            if (!jlayout || !jstyle) {
                break;
            }

            juicontext = env->CallStaticObjectMethod(localClassUIContext,
                                                     methodID_UI_createContext,
                                                     (jstring) jlayout,
                                                     (jstring) jstyle);

        } while (0);
        return juicontext;
    }

    void registerUI(const std::string &name, const std::string &layout) {

    }
};